package com.zhongxi.guoyuan.view.seller;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.seller.SellerBeautifulAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.seller.ConsoleCoinRecordDetailResult;
import com.zhongxi.guoyuan.entity.seller.DataCoinRecordDetailResult;
import com.zhongxi.guoyuan.entity.seller.InnerInfoResult;
import com.zhongxi.guoyuan.entity.seller.OrderDatas;
import com.zhongxi.guoyuan.entity.seller.SellerBeautifulOrderData;
import com.zhongxi.guoyuan.entity.seller.StatisticsCoinRecordDetailResult;
import com.zhongxi.guoyuan.entity.seller.SummaryResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.view.seller.provinceselector.ProvinceMainActivity;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SellerBeautifulStoreOrderActivity extends BaseActivity implements View.OnClickListener, MyScrollView.OnScrollListener {

    private TextView tvEndTime;
    private TextView tvStartTime;
    private DatePickerDialog dialog;
    private NoScrollListView lvList;
    private List<SellerBeautifulOrderData> orderData = new ArrayList<>();
    private String type;
    private Map<String, String> map = new HashMap<>();
    private String endTime;
    private String startTime;
    private RadioButton rb1;
    private RadioButton rb2;
    private RadioButton rb0;
    private TextView tvAllGoOrder;
    private TextView tvAllHomeOrder;
    private TextView tvAllHomeMDOrder;
    private TextView tvAllTimeOrderNum;
    private TextView tvTimeMoney;
    private TextView tvTimeHomeOrder;
    private TextView tvTimeHomeMDOrder;
    private TextView tvStore;
    private TextView tv_shopid;
    private TextView tvAllOrder;
    private int status = 1;
    private TextView tv_shop_name;
    private ImageView tvQuery;
    private SellerBeautifulAdapter adapter;
    private MyScrollView myScrollView;
    private boolean scroll;

    private static final long SCROLLTIME = 200;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = msg.getData().getInt("pos");
            switch (msg.what) {
                case 0:
                    type = "confirm";
                    map.clear();
                    map.put("orderid", msg.getData().getString("orderid"));
                    map.put("sid", msg.getData().getString("sid"));
                    getServer(Url.INNER_CONFIRM_ORDER, map, "", true, null, "post");
                    break;
                case 1:
                    type = "operate";
                    map.clear();
                    map.put("orderid", msg.getData().getString("orderid"));
                    map.put("sid", msg.getData().getString("sid"));
                    getServer(Url.INNER_OPTORDER, map, "", true, null, "post");
                    break;
            }
        }
    };
    public static final int requestCodeGetVaule = 234;
    private String shopid = "";

    private LinearLayout relaLayout;
    private boolean isMeasured;
    private LinearLayout scrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private int scrollHeight;
    private ImageView iv_verify;
    private RelativeLayout title;
    private EditText etPhone;
    private int pos;
    private String trim = "";
    private LinearLayout ll_select_store;
    private boolean issearch = false;

    private TextView et_hint_text;
    private TextView et_text_cancel;
    private TextView et_clear;


    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            myScrollView.fullScroll(MyScrollView.FOCUS_UP);
        }
    };

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_seller_beautiful_store_order);
        initTitle();
        tvTitle.setText("美容院总部");
        iv_verify = (ImageView) findViewById(R.id.iv_verify);
        title = (RelativeLayout) findViewById(R.id.title);
        myScrollView = (MyScrollView) findViewById(R.id.myScrollView);
        tvStore = (TextView) findViewById(R.id.tvStore);
        tv_shopid = (TextView) findViewById(R.id.tv_shopid);

        tvAllOrder = (TextView) findViewById(R.id.tvAllOrder);
        tvAllGoOrder = (TextView) findViewById(R.id.tvAllGoOrder);
        tvAllHomeOrder = (TextView) findViewById(R.id.tvAllHomeOrder);
        tvAllHomeMDOrder = (TextView) findViewById(R.id.tvAllHomeMDOrder);

        tvStartTime = (TextView) findViewById(R.id.tvStartTime);
        tvEndTime = (TextView) findViewById(R.id.tvEndTime);

        tvAllTimeOrderNum = (TextView) findViewById(R.id.tvAllTimeOrderNum);
        tvTimeMoney = (TextView) findViewById(R.id.tvTimeMoney);
        tvTimeHomeOrder = (TextView) findViewById(R.id.tvTimeHomeOrder);
        tvTimeHomeMDOrder = (TextView) findViewById(R.id.tvTimeHomeMDOrder);

        ll_select_store = (LinearLayout) findViewById(R.id.ll_select_store);
        tv_shop_name = (TextView) findViewById(R.id.tv_shop_name);
        tvQuery = (ImageView) findViewById(R.id.tvQuery);
        et_hint_text = (TextView) findViewById(R.id.et_hint_text);
        et_text_cancel = (TextView) findViewById(R.id.et_text_cancel);
        et_clear = (TextView) findViewById(R.id.et_clear);
        etPhone = (EditText) findViewById(R.id.etPhone);

        rb0 = (RadioButton) findViewById(R.id.rb0);
        rb1 = (RadioButton) findViewById(R.id.rb1);
        rb2 = (RadioButton) findViewById(R.id.rb2);

        lvList = (NoScrollListView) findViewById(R.id.lvList);

        //实现上拉布局悬停
        initScrollPause();
    }

    private void initScrollPause() {
        //滑动置顶
        scrollBody = (LinearLayout) findViewById(R.id.scrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);

        relaLayout = (LinearLayout) findViewById(R.id.relaLayout);
        ViewTreeObserver observer = relaLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    scrollHeight = relaLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
    }

    /**
     * 初始化数据
     *
     * @param result
     */
    private void initInfo(InnerInfoResult result) {
        if (null != result.getConsole() && !"".equals(result.getConsole())) {
            ConsoleCoinRecordDetailResult console = result.getConsole();
            if (null != console.getName() && !"".equals(console.getName())) {
                tvStore.setText(console.getName());
            } else {
                tvStore.setText("");
            }
            if (null != console.getMphone() && !"".equals(console.getMphone())) {
                tv_shopid.setText(console.getId());
            } else {
                tv_shopid.setText("");
            }
        }

        if (null != result.getStatistics() && !"".equals(result.getStatistics())) {
            StatisticsCoinRecordDetailResult statistics = result.getStatistics();
            if (null != statistics.getOrderNum() && !"".equals(statistics.getOrderNum())) {
                tvAllOrder.setText(statistics.getOrderNum());
            } else {
                tvAllOrder.setText("0");
            }
            if (null != statistics.getData() && !"".equals(statistics.getData())) {
                DataCoinRecordDetailResult info = statistics.getData();

                if (null != info.getInnerprice() && !"".equals(info.getInnerprice())) {
                    tvAllGoOrder.setText(info.getInnerprice());
                } else {
                    tvAllGoOrder.setText("0");
                }
                if (null != info.getPrice() && !"".equals(info.getPrice())) {
                    tvAllHomeOrder.setText(info.getPrice() + " + ");
                } else {
                    tvAllHomeOrder.setText("0 + ");
                }
                if (null != info.getRedbeanprice() && !"".equals(info.getRedbeanprice())) {
                    tvAllHomeMDOrder.setText(info.getRedbeanprice());
                } else {
                    tvAllHomeMDOrder.setText("0");
                }
            }
        }
    }


    @Override
    protected void initData() {
        super.initData();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(now);
        tvStartTime.setText(dateNowStr);
        tvEndTime.setText(dateNowStr);
        startTime = endTime = dateNowStr;
        adapter = new SellerBeautifulAdapter(context, orderData, handler);
        lvList.setAdapter(adapter);
        getSummary();
    }

    private void getSummary() {
        type = "info";
        getServer(Url.INNER_INFO, null, "", true, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        myScrollView.setOnScrollListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        rb0.setOnClickListener(this);
        rb1.setOnClickListener(this);
        rb2.setOnClickListener(this);
        tvQuery.setOnClickListener(this);
        ll_select_store.setOnClickListener(this);
        etPhone.setOnClickListener(this);
        et_clear.setOnClickListener(this);
        et_text_cancel.setOnClickListener(this);

        etPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if (b) {
                    et_text_cancel.setVisibility(View.VISIBLE);
                    et_text_cancel.setText("取消");
                    et_clear.setVisibility(View.GONE);
                    et_hint_text.setVisibility(View.GONE);
                }
            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    et_clear.setVisibility(View.VISIBLE);
                    et_text_cancel.setText("搜索");
                } else {
                    et_clear.setVisibility(View.GONE);
                    et_text_cancel.setText("取消");
//                    etTextCancel.setText("搜索");
                }
                et_hint_text.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvStartTime:
                showDateDialog(0);
                break;
            case R.id.tvEndTime:
                showDateDialog(1);
                break;
            case R.id.rb0:
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    handler.postDelayed(runnable, SCROLLTIME);
                }
                rb0.setChecked(true);
                rb1.setChecked(false);
                rb2.setChecked(false);
                status = 1;
                pageNum = 1;
                getOrder();
                break;
            case R.id.rb1:
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    handler.postDelayed(runnable, SCROLLTIME);
                }
                rb0.setChecked(false);
                rb1.setChecked(true);
                rb2.setChecked(false);
                status = 2;
                pageNum = 1;
                getOrder();
                break;
            case R.id.rb2:
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    handler.postDelayed(runnable, SCROLLTIME);
                }
                rb0.setChecked(false);
                rb1.setChecked(false);
                rb2.setChecked(true);
                status = 3;
                pageNum = 1;
                getOrder();
                break;
            case R.id.tvQuery:
                pageNum = 1;
                trim = etPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    if (!RegularTool.isPhoneNumberValid(trim)) {
                        showShortToast("请输入正确的手机号");
                        break;
                    }
                } else {
                    etPhone.setText("");
                    et_hint_text.setVisibility(View.VISIBLE);
                    et_clear.setVisibility(View.GONE);
                    et_text_cancel.setVisibility(View.GONE);
                }
                getOrder();

                issearch = true;
                CommonTool.hideSoft(etPhone, this);
                break;
            case R.id.et_clear:
                etPhone.setText("");
                et_hint_text.setVisibility(View.VISIBLE);
                et_text_cancel.setText("取消");
//                etTextCancel.setText("搜索");
                et_text_cancel.setVisibility(View.VISIBLE);
//                getData();
                CommonTool.hideSoft(etPhone, context);
                break;
            case R.id.et_text_cancel:
                pageNum = 1;
                trim = etPhone.getText().toString().trim();

                if (!TextUtils.isEmpty(trim)) {
                    if (!RegularTool.isPhoneNumberValid(trim)) {
                        showShortToast("请输入正确的手机号");
                        break;
                    }
                } else {
                    etPhone.setText("");
                    et_hint_text.setVisibility(View.VISIBLE);
                    et_clear.setVisibility(View.GONE);
                    et_text_cancel.setVisibility(View.GONE);
                }
                getOrder();

                issearch = true;
                CommonTool.hideSoft(etPhone, this);
                break;
            case R.id.etPhone:
                et_text_cancel.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_select_store:
                Intent intent = new Intent(this, ProvinceMainActivity.class);
                startActivityForResult(intent, requestCodeGetVaule);
                break;
        }
    }

    //    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String mon = month + 1 + "";
                String text = year + "-" + mon + "-" + dayOfMonth;
                if (index == 0) {
                    tvStartTime.setText(text);
                    startTime = text;
                } else if (index == 1) {
                    tvEndTime.setText(text);
                    endTime = text;
                }
                pageNum = 1;
                getQueryInfo();
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("info".equals(type)) {
                InnerInfoResult result = gson.fromJson(response, InnerInfoResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                initInfo(result);
                getQueryInfo();
            } else if ("queryInfo".equals(type)) {
                SummaryResult result = gson.fromJson(response, SummaryResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getStatistics() && !"".equals(result.getStatistics())) {
                    StatisticsCoinRecordDetailResult statistics = result.getStatistics();
                    getTimeOrderInfo(statistics);
                }
                getOrder();
            } else if ("order".equals(type)) {
                OrderDatas orderDatas = gson.fromJson(response, OrderDatas.class);
                MyApplication.getInstance().setSpValue(orderDatas.getSafeobj());
                if (pageNum == 1) {
                    orderData.clear();
                }
                if (orderDatas.getData() != null && orderDatas.getData().size() > 0) {
                    List<SellerBeautifulOrderData> listData = orderDatas.getData();
                    orderData.addAll(listData);
                    scroll = true;
                    adapter.setType(status);
                    JSONObject obj = new JSONObject(response);
                    JSONObject user = obj.optJSONObject("userInfo");
                    if (user != null && !"".equals(user)) {
                        adapter.setJSONObject(user);
                    }
                    JSONObject shopInfo = obj.optJSONObject("shopInfo");
                    if (null != shopInfo && !"".equals(shopInfo)) {
                        adapter.setShopInfo(shopInfo);
                    }
                    JSONObject complaints = obj.optJSONObject("complaints");
                    if (null != complaints && !"".equals(complaints)) {
                        adapter.setComplaints(complaints);
                    }
                } else {
                    if (pageNum > 1) {
                        pageNum--;
                    }
                    scroll = false;
                    if (issearch && trim.length() > 0) {
                        showShortToast("抱歉，搜索不到与该号码相关的订单");
                    }
                }
                issearch = false;
                adapter.notifyDataSetChanged();
            } else if ("confirm".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                orderData.remove(pos);
                adapter.notifyDataSetChanged();
                showShortToast("确认订单成功");
            } else if ("operate".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                orderData.remove(pos);
                adapter.notifyDataSetChanged();
                showShortToast("操作订单成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getTimeOrderInfo(StatisticsCoinRecordDetailResult statistics) {
        if (null != statistics.getOrderNum() && !"".equals(statistics.getOrderNum())) {
            tvAllTimeOrderNum.setText(statistics.getOrderNum());
        } else {
            tvAllTimeOrderNum.setText("0");
        }
        if (statistics.getData() != null && !"".equals(statistics.getData())) {
            DataCoinRecordDetailResult data = statistics.getData();
            if (null != data.getInnerprice() && !"".equals(data.getInnerprice())) {
                tvTimeMoney.setText(data.getInnerprice());
            } else {
                tvTimeMoney.setText("0");
            }
            if (null != data.getPrice() && !"".equals(data.getPrice())) {
                tvTimeHomeOrder.setText(data.getPrice() + " + ");
            } else {
                tvTimeHomeOrder.setText("0 + ");
            }
            if (null != data.getRedbeanprice() && !"".equals(data.getRedbeanprice())) {
                tvTimeHomeMDOrder.setText(data.getRedbeanprice());
            } else {
                tvTimeHomeMDOrder.setText("0");
            }
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if (result.getCode() == 1000) {

        } else if (result.getCode() == 9002) {
            showShortToast("登录已失效，请重新登录");
            MyApplication.getInstance().sharedPrefrences.edit().putString("beautifulcredentials", "").commit();
            finish();
        } else if (result.getCode() == 1666) {
            showShortToast("服务不可用，服务器异常");
        }
    }

    /**
     * 查询某个时间内的订单数
     */
    private void getQueryInfo() {
        if (CommonTool.TimeCompare(startTime, endTime)) {
            type = "queryInfo";
            map.clear();
            map.put("stime", startTime);
            map.put("etime", endTime);
            getServer(Url.INNER_ORDER_SUMMARY, map, "", true, null, "post");
        } else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    /**
     * 获取
     */
    private void getOrder() {
        type = "order";
        map.clear();
        map.put("userphone", trim);
        map.put("shopid", shopid);    //shopid
        map.put("status", status + "");
        String str = "&page=" + pageNum;
        getServer(Url.INNER_ORDER_STATUS, map, str, true, null, "post");
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= scrollHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(scrollBody.getMeasuredWidth(), scrollBody.getMeasuredHeight()));
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (!MyTextUtils.isFastDoubleClick() && scroll) {
            pageNum++;
            getOrder();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestCodeGetVaule && resultCode == ProvinceMainActivity.resultCodeValu) {
            String name = data.getStringExtra("key");
            shopid = data.getStringExtra("value");
            tv_shop_name.setText(name);
            pageNum = 1;
            getOrder();
        }
    }
}
